import React, { useState, useEffect } from 'react';
import { 
  Button, 
  Input, 
  Table, 
  Card, 
  Row, 
  Col, 
  Space, 
  Typography,
  Modal,
  Form,
  Select,
  message,
  InputNumber
} from 'antd';
import { BarChartOutlined, PlusOutlined, DeleteOutlined, EyeOutlined, EditOutlined, SyncOutlined } from '@ant-design/icons';
import dayjs from 'dayjs';
import ProfitText from '../../components/ProfitText';
import { STOCKS_STORAGE_KEY, TRANSACTIONS_STORAGE_KEY, STOCK_PRICES_STORAGE_KEY } from '../../utils/storageKeys';
import { calculateStockProfit, calculateTotalProfit } from '../../utils/profitCalculations';
import './index.less';

const { Title, Text } = Typography;
const { Option } = Select;

interface Stock {
  id: string;
  name?: string;
  code: string;
  quantity: number;
  cost: number;
}

interface Transaction {
  id: string;
  direction: 'buy' | 'sell';
  unitPrice: number;
  quantity: number;
  amount: number;
  timestamp: string;
}

interface StockFormValues {
  name?: string;
  code: string;
  quantity: number;
  unitCost: number;
}

interface TransactionFormValues {
  direction: 'buy' | 'sell';
  quantity: number;
  unitPrice: number;
}

interface PriceFormValues {
  price: number;
}

interface CalculatedStock extends Stock {
  currentValue: string;
  profit: string;
  profitRate: string;
  profitValue: number;
}

const ProfitCalculator: React.FC = () => {
  const [stocks, setStocks] = useState<Stock[]>([]);
  const [transactions, setTransactions] = useState<Record<string, Transaction[]>>({});
  const [stockPrices, setStockPrices] = useState<Record<string, number>>({});
  const [isAddStockModalVisible, setIsAddStockModalVisible] = useState<boolean>(false);
  const [isTransactionModalVisible, setIsTransactionModalVisible] = useState<boolean>(false);
  const [isViewTransactionsModalVisible, setIsViewTransactionsModalVisible] = useState<boolean>(false);
  const [isUpdatePriceModalVisible, setIsUpdatePriceModalVisible] = useState<boolean>(false);
  const [currentStockId, setCurrentStockId] = useState<string | null>(null);
  const [currentStockName, setCurrentStockName] = useState<string>('');
  const [transactionForm] = Form.useForm<TransactionFormValues>();
  const [stockForm] = Form.useForm<StockFormValues>();
  const [priceForm] = Form.useForm<PriceFormValues>();
  
  // 从本地存储加载数据
  useEffect(() => {
    const savedStocks = localStorage.getItem(STOCKS_STORAGE_KEY);
    const savedTransactions = localStorage.getItem(TRANSACTIONS_STORAGE_KEY);
    const savedStockPrices = localStorage.getItem(STOCK_PRICES_STORAGE_KEY);
    
    if (savedStocks) {
      setStocks(JSON.parse(savedStocks));
    }
    
    if (savedTransactions) {
      setTransactions(JSON.parse(savedTransactions));
    }
    
    if (savedStockPrices) {
      setStockPrices(JSON.parse(savedStockPrices));
    }
  }, []);
  
  // 保存股票数据到本地存储
  const saveStocksToLocalStorage = (stocksData: Stock[]) => {
    localStorage.setItem(STOCKS_STORAGE_KEY, JSON.stringify(stocksData));
  };
  
  // 保存交易数据到本地存储
  const saveTransactionsToLocalStorage = (transactionsData: Record<string, Transaction[]>) => {
    localStorage.setItem(TRANSACTIONS_STORAGE_KEY, JSON.stringify(transactionsData));
  };
  
  // 保存股票价格数据到本地存储
  const saveStockPricesToLocalStorage = (pricesData: Record<string, number>) => {
    localStorage.setItem(STOCK_PRICES_STORAGE_KEY, JSON.stringify(pricesData));
  };
  
  // 添加新股票
  const handleAddStock = (values: StockFormValues) => {
    const quantity = parseFloat(values.quantity.toString());
    const unitCost = parseFloat(values.unitCost.toString());
    const totalCost = quantity * unitCost;
    
    const newStock: Stock = {
      id: Date.now().toString(),
      name: values.name || '',
      code: values.code,
      quantity: quantity,
      cost: totalCost
    };
    
    const newStocks = [...stocks, newStock];
    setStocks(newStocks);
    saveStocksToLocalStorage(newStocks);
    
    // 将初始持仓数据作为第一条交易记录
    const initialTransaction: Transaction = {
      id: `init_${Date.now()}`,
      direction: 'buy',
      unitPrice: unitCost,
      quantity: quantity,
      amount: totalCost,
      timestamp: new Date().toISOString()
    };
    
    const newTransactions = { ...transactions, [newStock.id]: [initialTransaction] };
    setTransactions(newTransactions);
    saveTransactionsToLocalStorage(newTransactions);
    
    setIsAddStockModalVisible(false);
    stockForm.resetFields();
  };
  
  // 删除股票
  const handleDeleteStock = (stockId: string) => {
    const newStocks = stocks.filter(stock => stock.id !== stockId);
    setStocks(newStocks);
    saveStocksToLocalStorage(newStocks);
    
    // 同时删除该股票的交易记录
    const newTransactions = { ...transactions };
    delete newTransactions[stockId];
    setTransactions(newTransactions);
    saveTransactionsToLocalStorage(newTransactions);
    
    // 同时删除该股票的价格记录
    const newStockPrices = { ...stockPrices };
    delete newStockPrices[stockId];
    setStockPrices(newStockPrices);
    saveStockPricesToLocalStorage(newStockPrices);
  };
  
  // 打开交易记录模态框
  const openTransactionModal = (stockId: string) => {
    setCurrentStockId(stockId);
    setIsTransactionModalVisible(true);
    transactionForm.resetFields();
  };
  
  // 打开查看交易记录模态框
  const openViewTransactionsModal = (stockId: string, stockName: string) => {
    setCurrentStockId(stockId);
    setCurrentStockName(stockName);
    setIsViewTransactionsModalVisible(true);
  };
  
  // 打开更新股价模态框
  const openUpdatePriceModal = (stockId: string, stockName: string) => {
    setCurrentStockId(stockId);
    setCurrentStockName(stockName);
    setIsUpdatePriceModalVisible(true);
    // 设置默认价格为当前价格
    const currentPrice = stockPrices[stockId] || 0;
    priceForm.setFieldsValue({ price: currentPrice });
  };
  
  // 更新股价
  const handleUpdatePrice = (values: PriceFormValues) => {
    if (!currentStockId) return;
    
    const newStockPrices = { ...stockPrices, [currentStockId]: parseFloat(values.price.toString()) };
    setStockPrices(newStockPrices);
    saveStockPricesToLocalStorage(newStockPrices);
    
    // 更新股票数据以反映新的价格计算
    const updatedStocks = stocks.map(stock => {
      if (stock.id === currentStockId) {
        const stockTransactions = transactions[currentStockId] || [];
        return calculateStockProfit(stock, stockTransactions, parseFloat(values.price.toString()));
      }
      return stock;
    });
    
    setStocks(updatedStocks);
    saveStocksToLocalStorage(updatedStocks);
    
    setIsUpdatePriceModalVisible(false);
    priceForm.resetFields();
    message.success('股价更新成功');
  };
  
  // 添加交易记录
  const handleAddTransaction = (values: TransactionFormValues) => {
    if (!currentStockId) return;
    
    const quantity = parseFloat(values.quantity.toString());
    const unitPrice = parseFloat(values.unitPrice.toString());
    const amount = quantity * unitPrice;
    
    const newTransaction: Transaction = {
      id: Date.now().toString(),
      direction: values.direction,
      unitPrice: unitPrice,
      quantity: quantity,
      amount: amount,
      timestamp: new Date().toISOString()
    };
    
    const stockTransactions = transactions[currentStockId] || [];
    const newStockTransactions = [...stockTransactions, newTransaction];
    
    const newTransactions = {
      ...transactions,
      [currentStockId]: newStockTransactions
    };
    
    setTransactions(newTransactions);
    saveTransactionsToLocalStorage(newTransactions);
    
    // 更新股票数据
    const updatedStocks = stocks.map(stock => {
      if (stock.id === currentStockId) {
        const currentPrice = stockPrices[currentStockId] || null;
        return calculateStockProfit(stock, newStockTransactions, currentPrice);
      }
      return stock;
    });
    
    setStocks(updatedStocks);
    saveStocksToLocalStorage(updatedStocks);
    
    setIsTransactionModalVisible(false);
    transactionForm.resetFields();
  };
  
  // 获取当前股票的交易记录
  const getCurrentStockTransactions = (): Transaction[] => {
    if (!currentStockId) return [];
    return transactions[currentStockId] || [];
  };
  
  // 交易记录表格列定义
  const transactionColumns = [
    {
      title: '交易时间',
      dataIndex: 'timestamp',
      key: 'timestamp',
      render: (timestamp: string) => dayjs(timestamp).format('YYYY-MM-DD HH:mm:ss')
    },
    {
      title: '交易方向',
      dataIndex: 'direction',
      key: 'direction',
      render: (direction: string) => direction === 'buy' ? '买入' : '卖出'
    },
    {
      title: '交易数量',
      dataIndex: 'quantity',
      key: 'quantity',
    },
    {
      title: '单位价格',
      dataIndex: 'unitPrice',
      key: 'unitPrice',
      render: (unitPrice: number) => unitPrice ? unitPrice.toFixed(2) : '-'
    },
    {
      title: '交易金额',
      dataIndex: 'amount',
      key: 'amount',
    },
    {
      title: '盈亏金额',
      key: 'profit',
      render: (_: any, record: Transaction) => {
        // 只有买入记录才计算盈亏
        if (record.direction !== 'buy' || !currentStockId) return '-';
        
        const currentPrice = stockPrices[currentStockId] || 0;
        if (currentPrice <= 0) return '-';
        
        const unitPrice = parseFloat(record.unitPrice.toString()) || 0;
        const quantity = parseFloat(record.quantity.toString()) || 0;
        const profit = (currentPrice - unitPrice) * quantity;
        
        return <ProfitText profitValue={profit} text={profit.toFixed(2)} />;
      }
    },
    {
      title: '盈亏比例',
      key: 'profitRate',
      render: (_: any, record: Transaction) => {
        // 只有买入记录才计算盈亏比例
        if (record.direction !== 'buy' || !currentStockId) return '-';
        
        const currentPrice = stockPrices[currentStockId] || 0;
        if (currentPrice <= 0) return '-';
        
        const unitPrice = parseFloat(record.unitPrice.toString()) || 0;
        if (unitPrice <= 0) return '-';
        
        const profitRate = ((currentPrice - unitPrice) / unitPrice) * 100;
        
        return <ProfitText profitValue={profitRate} text={`${profitRate.toFixed(2)}%`} />;
      }
    }
  ];
  
  // 股票表格列定义
  const stockColumns = [
    {
      title: '股票名称',
      dataIndex: 'name',
      key: 'name',
      render: (_: any, record: Stock) => record.name || record.code
    },
    {
      title: '股票代码',
      dataIndex: 'code',
      key: 'code',
    },
    {
      title: '持仓份额',
      dataIndex: 'quantity',
      key: 'quantity',
      render: (_: any, record: Stock) => {
        const stockTransactions = transactions[record.id] || [];
        const currentPrice = stockPrices[record.id] || null;
        const calculated = calculateStockProfit(record, stockTransactions, currentPrice);
        return calculated.quantity;
      }
    },
    {
      title: '持仓成本',
      dataIndex: 'cost',
      key: 'cost',
      render: (_: any, record: Stock) => {
        const stockTransactions = transactions[record.id] || [];
        const currentPrice = stockPrices[record.id] || null;
        const calculated = calculateStockProfit(record, stockTransactions, currentPrice);
        return calculated.cost;
      }
    },
    {
      title: '当前价格',
      dataIndex: 'currentPrice',
      key: 'currentPrice',
      render: (_: any, record: Stock) => {
        const currentPrice = stockPrices[record.id] || 0;
        return currentPrice > 0 ? currentPrice.toFixed(2) : '未设置';
      }
    },
    {
      title: '当前价值',
      dataIndex: 'currentValue',
      key: 'currentValue',
      render: (_: any, record: Stock) => {
        const stockTransactions = transactions[record.id] || [];
        const currentPrice = stockPrices[record.id] || null;
        const calculated = calculateStockProfit(record, stockTransactions, currentPrice);
        return calculated.currentValue;
      }
    },
    {
      title: '盈利',
      dataIndex: 'profit',
      key: 'profit',
      render: (_: any, record: Stock) => {
        const stockTransactions = transactions[record.id] || [];
        const currentPrice = stockPrices[record.id] || null;
        const calculated = calculateStockProfit(record, stockTransactions, currentPrice);
        return <ProfitText profitValue={calculated.profitValue} text={calculated.profit} />;
      }
    },
    {
      title: '盈利率',
      dataIndex: 'profitRate',
      key: 'profitRate',
      render: (_: any, record: Stock) => {
        const stockTransactions = transactions[record.id] || [];
        const currentPrice = stockPrices[record.id] || null;
        const calculated = calculateStockProfit(record, stockTransactions, currentPrice);
        return <ProfitText profitValue={calculated.profitValue} text={calculated.profitRate} />;
      }
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: Stock) => (
        <Space>
          <Button 
            type="primary" 
            icon={<EditOutlined />} 
            size="small"
            onClick={() => openTransactionModal(record.id)}
          >
            交易
          </Button>
          <Button 
            icon={<SyncOutlined />} 
            size="small"
            onClick={() => openUpdatePriceModal(record.id, record.name || record.code)}
          >
            更新股价
          </Button>
          <Button 
            icon={<EyeOutlined />} 
            size="small"
            onClick={() => openViewTransactionsModal(record.id, record.name || record.code)}
          >
            查看记录
          </Button>
          <Button 
            icon={<DeleteOutlined />} 
            size="small"
            danger
            onClick={() => handleDeleteStock(record.id)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <div className="profit-calculator">
      <Card title={
        <Space>
          <BarChartOutlined />
          <span>股票盈利计算</span>
        </Space>
      }>
        <div style={{ marginBottom: 16, textAlign: 'right' }}>
          <Button 
            type="primary" 
            icon={<PlusOutlined />}
            onClick={() => setIsAddStockModalVisible(true)}
          >
            添加股票
          </Button>
        </div>
        
        {stocks.length > 0 ? (
          <>
            <Table 
              dataSource={stocks} 
              columns={stockColumns} 
              pagination={false} 
              rowKey="id"
              size="middle"
            />
            
            <Card title="汇总信息" size="small" style={{ marginTop: 16 }}>
              <Row gutter={16}>
                <Col span={6}>
                  <Text strong>股票数量: </Text>
                  <Text>{stocks.length} 只</Text>
                </Col>
                <Col span={6}>
                  <Text strong>总成本: </Text>
                  <Text>{calculateTotalProfit(stocks, transactions, stockPrices).totalCost} 元</Text>
                </Col>
                <Col span={6}>
                  <Text strong>总价值: </Text>
                  <Text>{calculateTotalProfit(stocks, transactions, stockPrices).totalValue} 元</Text>
                </Col>
                <Col span={6}>
                  <Text strong>总盈亏: </Text>
                  <ProfitText 
                    profitValue={parseFloat(calculateTotalProfit(stocks, transactions, stockPrices).totalProfit)} 
                    text={`${calculateTotalProfit(stocks, transactions, stockPrices).totalProfit} 元 (${calculateTotalProfit(stocks, transactions, stockPrices).totalProfitRate})`} 
                  />
                </Col>
              </Row>
            </Card>

          </>
        ) : (
          <div style={{ textAlign: 'center', padding: '40px' }}>
            <Text type="secondary">暂无股票数据，请点击"添加股票"按钮添加</Text>
          </div>
        )}
      </Card>
      
      {/* 添加股票模态框 */}
      <Modal
        title="添加股票"
        open={isAddStockModalVisible}
        onCancel={() => {
          setIsAddStockModalVisible(false);
          stockForm.resetFields();
        }}
        onOk={() => stockForm.submit()}
      >
        <Form
          form={stockForm}
          layout="vertical"
          onFinish={handleAddStock}
        >
          <Form.Item
            name="name"
            label="股票名称"
          >
            <Input placeholder="请输入股票名称（非必填）" />
          </Form.Item>
          
          <Form.Item
            name="code"
            label="股票代码"
            rules={[{ required: true, message: '请输入股票代码' }]}
          >
            <Input placeholder="请输入股票代码" />
          </Form.Item>
          
          <Form.Item
            name="quantity"
            label="持仓数量"
            rules={[{ required: true, message: '请输入持仓数量' }]}
          >
            <InputNumber style={{ width: '100%' }} step={0.01} placeholder="请输入持仓数量" />
          </Form.Item>
          
          <Form.Item
            name="unitCost"
            label="单位成本价"
            rules={[{ required: true, message: '请输入单位成本价' }]}
          >
            <InputNumber style={{ width: '100%' }} step={0.01} placeholder="请输入单位成本价" />
          </Form.Item>
        </Form>
      </Modal>
      
      {/* 交易记录模态框 */}
      <Modal
        title="添加交易记录"
        open={isTransactionModalVisible}
        onCancel={() => {
          setIsTransactionModalVisible(false);
          transactionForm.resetFields();
        }}
        onOk={() => transactionForm.submit()}
      >
        <Form
          form={transactionForm}
          layout="vertical"
          onFinish={handleAddTransaction}
        >
          <Form.Item
            name="direction"
            label="交易方向"
            rules={[{ required: true, message: '请选择交易方向' }]}
          >
            <Select placeholder="请选择交易方向">
              <Option value="buy">买入</Option>
              <Option value="sell">卖出</Option>
            </Select>
          </Form.Item>
          
          <Form.Item
            name="quantity"
            label="交易数量"
            rules={[{ required: true, message: '请输入交易数量' }]}
          >
            <InputNumber style={{ width: '100%' }} step={0.01} placeholder="请输入交易数量" />
          </Form.Item>
          
          <Form.Item
            name="unitPrice"
            label="交易单位价格"
            rules={[{ required: true, message: '请输入交易单位价格' }]}
          >
            <InputNumber style={{ width: '100%' }} step={0.01} placeholder="请输入交易单位价格" />
          </Form.Item>
        </Form>
      </Modal>
      
      {/* 查看交易记录模态框 */}
      <Modal
        title={`交易记录 - ${currentStockName}`}
        open={isViewTransactionsModalVisible}
        onCancel={() => setIsViewTransactionsModalVisible(false)}
        footer={[
          <Button key="close" onClick={() => setIsViewTransactionsModalVisible(false)}>
            关闭
          </Button>
        ]}
        width={800}
      >
        <Table
          dataSource={getCurrentStockTransactions()}
          columns={transactionColumns}
          pagination={{ pageSize: 5 }}
          rowKey="id"
        />
      </Modal>
      
      {/* 更新股价模态框 */}
      <Modal
        title={`更新股价 - ${currentStockName}`}
        open={isUpdatePriceModalVisible}
        onCancel={() => {
          setIsUpdatePriceModalVisible(false);
          priceForm.resetFields();
        }}
        onOk={() => priceForm.submit()}
      >
        <Form
          form={priceForm}
          layout="vertical"
          onFinish={handleUpdatePrice}
        >
          <Form.Item
            name="price"
            label="当前股价"
            rules={[{ required: true, message: '请输入当前股价' }]}
          >
            <InputNumber
              style={{ width: '100%' }}
              placeholder="请输入当前股价"
              min={0}
              step={0.01}
            />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default ProfitCalculator;